/*
 * @lc app=leetcode.cn id=538 lang=cpp
 *
 * [538] 把二叉搜索树转换为累加树
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    TreeNode *convertBST(TreeNode *root) {
        int sum = 0;             // 记录当前的值之和
        TreeNode *node = root;   // 记录当前正在访问的节点
        stack<TreeNode *> tree;  // 记录尚未访问的节点的栈

        // 倒转的中序遍历
        while (!tree.empty() || root != nullptr) {
            // 寻找最右子节点，即最大值
            while (root != nullptr) {
                tree.push(root);
                root = root->right;
            }

            //访问并修改当前节点
            root = tree.top();
            tree.pop();
            sum += root->val;
            root->val = sum;
            
            // 访问当前节点的左子树
            root = root->left;
        }

        return node;
    }
};
// @lc code=end
